import { Button, Statistic, Tooltip,AutoComplete, message, Card, Row, Col, Input } from 'antd';
import React, {
  useState,
  useRef
} from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { queryRule, selectActivity,queryInfo,userExport,activityExport} from './service';
import { Link } from "react-router-dom"
import moment from 'moment';
import { downloadFile } from '../../../utils/utils'
import ProCard from '@ant-design/pro-card';
const { Option } = AutoComplete;
const TableList=() => {
  const actionRef = useRef();
  const [options, setOptions] = useState<{ value: string }[]>([]);
  const [firstRender,setFirstRender] = useState<boolean>(true)
  const [activityId, setActivityId] = useState<any>()
  const [baseInfo, setBaseInfo] = useState<any>()
  const statusMap = {
    '0': '未开始',
    '1': '已开始',
    '2': '已完成'
  }
  const onSelect = (value: any, option: any) => {
    setActivityId(option.key)
  };
  const onSearch = async (key: string) => {
    let data = await selectActivity({ key})
    let options = !key ? [] : data.data.map((item: { activityId: any; activityName: any; }) => ({id: item.activityId, label: item.activityName, value: item.activityId}))
    setOptions(options);
  };
  const userExportHandler = async function () {
    if (!activityId) {
      message.error('请选择或者输入课程id')
      return
    }
    const url = await userExport({activityId:String(activityId)})
    downloadFile(`课程学员出勤统计-${baseInfo.classroomName}-${baseInfo.teacherName}-${moment(new Date().getTime()).format('YYYY-MM-DD HH-mm-ss')}`,url,'.xls')
  }
  const activityExportHandler = async function () {
    if (!activityId) {
      message.error('请选择或者输入课程id')
      return
    }
    const url = await activityExport({activityId:String(activityId)})
    downloadFile(`课程条目出勤统计-${baseInfo.classroomName}-${baseInfo.teacherName}-${moment(new Date().getTime()).format('YYYY-MM-DD HH-mm-ss')}`,url,'.xls')
  }
  const columns: ProColumns<{}>[] = [
    {
      title: '课程ID',
      dataIndex: 'activityId',
    },
    {
      title: '课程名称',
      dataIndex: 'key',
      hideInTable: true,
      renderFormItem: (text, props) =>
        <AutoComplete
          onSelect={onSelect}
          onSearch={onSearch}
          placeholder="请选择"
          onChange={(value) => {
            if (!value) {
              setActivityId()
            }
           }}
        >
           {options.map((item) => (
            <Option key={item.id}  label={item.label} value={item.label}>
              {item.label}
            </Option>
          ))}
        </AutoComplete>,
    },
    {
      title: '课程名称',
      dataIndex: 'activityName',
      hideInSearch: true,
      ellipsis:true,
      width: 150,
      copyable: true,
      tip: '标题过长会自动收缩',
    },
    {
      title: '条目名称',
      dataIndex: 'classroomName',
      hideInSearch: true,
      copyable: true,
      tip: '标题过长会自动收缩',
      render: (_, record) => (
        <Tooltip title={record.classroomName} placement="top">
          <Link target="_blank" to={`/activity/activity-class-data?classroomId=${record.classroomId}`} style={{width:150,textOverflow:'ellipsis',whiteSpace:'nowrap',display:'inline-block',overflow:'hidden'} }>
            { record.classroomName}
          </Link>
        </Tooltip>
      ),
    },
    {
      title: '上课时间',
      dataIndex: 'startTime',
      hideInSearch: true,
      render: (startTime,record) =>
        <>{ record.startTime ? moment(startTime*1000).format('YYYY-MM-DD HH:mm:ss'):'-'}</>

    },
    {
      title: '到课人数',
      dataIndex: 'attendanceNum',
      hideInSearch: true,
    },
    {
      title: '应到人数',
      dataIndex: 'allNum',
      hideInSearch:true
    },
    {
      title: '标记选择题正确率',
      dataIndex: 'signAccuracy',
      hideInSearch: true,
      render: (signAccuracy, record) => (<>{ record.signAccuracy ? (signAccuracy*100).toFixed(1) + '%':'-'}</>)
    },
    {
      title: '互动课件正确率',
      dataIndex: 'interactAccuracy',
      hideInSearch: true,
      render: (interactAccuracy, record) => (<>{ record.interactAccuracy  ? (interactAccuracy*100).toFixed(1) + '%':'-'}</>)
    },
  ];


  const isNumber = (val) => {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if(regPos.test(val) || regNeg.test(val)) {
        return true;
        } else {
        return false;
        }
    }

  return (

    <PageContainer>
      <ProTable<{}>
        headerTitle="数据列表"
        actionRef={actionRef}
        rowKey="key"
        request={async params => {

          let _activityId = activityId ? activityId : params.activityId
          params.activityId = _activityId
          if (!isNumber(params.activityId) && !firstRender) {
              message.error('课程ID只能是数字')
              return
            }
          if (
              !params.activityId
              && !activityId
              && !firstRender
            ) {
              message.error('请选择或者输入课程id')
              return
            }
          const msg = await queryRule({
            ...params,
            pageNum: params.current
          })
           return {
            data: msg.data.classrooms === null?[]:msg.data.classrooms,
            success: true,
            total: msg.data.count
          }
        }}
        tableExtraRender={(props, dataSource) =>
         baseInfo&&
            <Card>
              <div style={{display:'flex'}}>
                <div
                  style={{marginRight:'20px'}}
                >主讲老师 :
                <span style={{fontSize:'17px',paddingLeft:'10px'}}>
                  {baseInfo.teacherName}
                  </span>
                </div>
                <div
                  style={{marginRight:'20px'}}
                  >课程进行至:
                  <span
                  style={{fontSize:'17px',paddingLeft:'10px'}}>
                    {baseInfo.status == 1? baseInfo.classroomName : statusMap[baseInfo.status]}
                  </span>
                 </div>
              </div>
            </Card>

        }
        columns={columns}

        toolBarRender={
          () => (
            [
              <Button key="primary" type="primary" onClick={userExportHandler}>
                导出课程学员出勤统计
              </Button>,
              <Button key="primary" type="primary" onClick={activityExportHandler}>
                导出课程条目出勤统计
              </Button>
            ]
          )
        }
        onReset={() => {
          window.location.reload()
        }}
        onSubmit={
          async (params) => {

            // let _activityId = activityId ? activityId : params.activityId
            let _activityId =  params.activityId ?  params.activityId : activityId

            params.activityId = _activityId
            setActivityId( params.activityId)
            setFirstRender(false)
            const info = await queryInfo({ activityId:params.activityId })
            setBaseInfo(info.data)
            return params


          }
      }
      />
    </PageContainer>
  );
};

export default TableList;
